package cn._2dland.uploader.utils;

import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn._2dland.uploader.Console;


public class Logger {
	/** 时间格式化 */
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/** 上传日志写入器 */
	private static PrintWriter logWriter = null;
	/** 错误日志写入器 */
	private static PrintWriter errWriter = null;
	/** 调试标志 */
	private static boolean debugMode = false;

	// 初始化日志文件
	static {
		String home = System.getProperty("user.dir");
		String fileSep = System.getProperty("file.separator");
		if(!home.endsWith(fileSep))
			home += fileSep;

		String logFile = home + "upload.log";
		try {
			logWriter = new PrintWriter(new FileOutputStream(logFile, true), true);
		} catch (Exception e) {
			e.printStackTrace(System.err);
		}

		String errFile = home + "error.log";
		try {
			errWriter = new PrintWriter(new FileOutputStream(errFile, true), true);
		} catch (Exception e) {
			e.printStackTrace(System.err);
		}
	}

	/**
	 * 向控制台输出信息
	 * @param info
	 */
	public static void writec(String info) {
		StringBuffer buf = new StringBuffer("[JUploader] ");
		System.out.println(buf.append(info));
	}

	/**
	 * 向日志文件输出信息
	 * @param info
	 */
	public static void writef(String info) {
		if(logWriter == null)
			return;
		StringBuffer buf = new StringBuffer("[").append(sdf.format(new Date())).append("] ");
		logWriter.println(buf.append(info));
	}

	/**
	 * 同时向控制台和日志文件输出信息
	 * @param info
	 */
	public static void writecf(String info) {
		writec(info);
		writef(info);
	}

	/**
	 * 向控制台同一行重复输出信息
	 * @param info
	 */
	public static void rewritec(String info) {
		// 用空格清空该行
		//int bufWidth = Console.getInstance().getScreenBufferWidth();
		int bufWidth = 80;
		StringBuffer blankBuf = new StringBuffer("\r");
		while(--bufWidth > 0)
			blankBuf.append(" ");
		System.out.print(blankBuf.toString());

		// 输出目标内容
		System.out.print("\r[JUploader] " + info);
	}

	/**
	 * 修改控制台标题
	 * @param info
	 */
	public static void writet(String info) {
		StringBuffer buf = new StringBuffer("JUploader - ");
		Console.getInstance().setTitle(buf.append(info).toString());
	}

	/**
	 * 记录异常信息
	 * @param e
	 */
	public static void error(Exception e) {
		e.printStackTrace(errWriter);
	}

	/**
	 * 设置调试模式（开启/关闭）
	 * @param debug
	 */
	public static void setDebug(boolean debug) {
		debugMode = debug;
	}

	/**
	 * 输出调试信息，仅当debug模式开启时才会输出
	 * @param info 信息
	 */
	public static void debug(String info) {
		if(!debugMode) return;

		StringBuffer buf = new StringBuffer("[DEBUG] ");
		System.out.println(buf.append(info));
	}
}